package com.rabbit.order.repository;

import com.rabbit.order.domain.OrderDAO;
import com.rabbit.order.domain.OrderDB;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;

@Repository
public class OrderRepository {

    public void addOrder(OrderDAO order,String userId){
        List<OrderDAO> orderDAOS = OrderDB.orderDB.get(userId);
        if(Objects.isNull(orderDAOS)){
            orderDAOS = new ArrayList<>();
            orderDAOS.add(order);
            OrderDB.orderDB.put(userId, orderDAOS);
        }else {
            orderDAOS.add(order);
        }
    }


    public void deleteOrder(OrderDAO order, String userId){
        List<OrderDAO> orderDAOS = OrderDB.orderDB.get(userId);
        orderDAOS.remove(order);
    }

    public List<OrderDAO> getOrders(String userId){
        return OrderDB.orderDB.get(userId);
    }

    public Boolean updateOrderSuc(String orderId, String userId) {
        List<OrderDAO> orderDAOS = OrderDB.orderDB.get(userId);
        AtomicReference<Boolean> result = new AtomicReference<>(false);
        orderDAOS.forEach(item->{
            if(orderId.equals(item.getOrderId()) && item.getOrderStatus().equals("start")){
                item.setOrderStatus("suc");
                result.set(true);
            }
        });
        return result.get();
    }
    public void updateOrderError(String orderId, String userId) {
        List<OrderDAO> orderDAOS = OrderDB.orderDB.get(userId);
        orderDAOS.forEach(item->{
            if(orderId.equals(item.getOrderId()) && item.getOrderStatus().equals("start")){
                item.setOrderStatus("error");
            }
        });
    }
}